package edu.nctu.csie.jichang.database.model.cell;

import java.util.LinkedHashMap;
import java.util.Map;

import edu.nctu.csie.jichang.database.util.StringUtil;

@SuppressWarnings("rawtypes")
public class AbstractContainer<E extends AbstractRootElement> extends AbstractRootElement<AbstractContainer<E>>{

	protected Map<String,E> container;
	
	public AbstractContainer(){
		this("".intern());
	}
	
	public AbstractContainer(String pContent) {
		super(pContent);
		container = new LinkedHashMap<String,E>();
	}
	public int getCount(){
		return container.size();
	}
	protected boolean hasChild(String pName) {
		return container.containsKey(pName);
	}
	protected Map<String,E> getChildren(){
		return container;
	}
	protected void addChild(String pKey,E pElement) {
		container.put(pKey, pElement);
	}
	protected void removeChild(String pKey) {
		container.remove(pKey);
	}
	protected E getChild(String pKey) {
		return container.get(pKey);
	}
	protected String[] getAllNames() {
		return container.keySet().toArray(new String[0]);
	}

	@SuppressWarnings("unchecked")
	@Override
	public boolean isSame(AbstractContainer<E> pElement) {
		if(!getName().equals(pElement.getName())) return false;
		E tElement1 = null;
		E tElement2 = null;
		for(String tName : getAllNames()){
			int tCredit1 = StringUtil.isEmptyOrSpace(tElement1 = getChild(tName)) ? 0 : 1 ;
			int tCredit2 = StringUtil.isEmptyOrSpace(tElement2 = pElement.getChild(tName)) ? 0 : 1 ;
			switch (tCredit1+tCredit2) {
				case 1:
					return false;
				case 2:
					if(!tElement1.isSame(tElement2)) return false;
			}
		}
		return false;
	}
}